package com.example.synccenter.identitysource.processor;

import com.example.synccenter.entity.DeptSyncRecordEntity;
import com.example.synccenter.service.DeptSyncRecordService;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.UUID;

/**
 * 默认身份源部门后处理器，实现部门数据的同步后处理逻辑。
 */
@Slf4j
@Component
public class DefaultIdentitySourceDeptPostProcessor extends AbstractIdentitySourcePostProcessor {
    @Autowired
    private DeptSyncRecordService deptSyncRecordService;

    /**
     * 构造方法，指定处理器名称
     */
    public DefaultIdentitySourceDeptPostProcessor() {
        super("部门后处理器");
    }

    /**
     * 实现部门数据的具体处理逻辑
     *
     * @param data    部门数据
     * @param context 同步上下文
     */
    @Override
    protected void doProcess(Map<String, Object> data, Map<String, Object> context) {
        // 从上下文中获取必要信息
        String sourceType = (String) context.get("sourceType");
        String getSourceDeptId = (String) context.get("sourceDeptId");
        String getLocalDeptId = (String) context.get("localDeptId");
        String sourceDeptId = StringUtil.isEmpty(getSourceDeptId) ? "source-dept-id" : getSourceDeptId;
        String localDeptId = StringUtil.isEmpty(getLocalDeptId) ? "local-dept-id" : getLocalDeptId;

        int deptCount = (Integer) data.getOrDefault("depts", 0);

        log.info("处理{}身份源部门数据: {}个", sourceType, deptCount);

        try {
            // 写入同步记录
            DeptSyncRecordEntity record = new DeptSyncRecordEntity();
            record.setId(UUID.randomUUID().toString());
            record.setTaskId((String) context.get("taskId"));
            record.setSourceDeptId(sourceDeptId);
            record.setLocalDeptId(localDeptId);
            record.setOperation("同步");
            record.setStatus("成功");
            record.setErrorMessage(null);
            deptSyncRecordService.save(record);
            log.info("{}身份源部门同步记录保存成功: {}", sourceType, sourceDeptId);
        } catch (Exception e) {
            log.error("{}身份源部门同步记录保存失败: {}", sourceType, e.getMessage(), e);
            throw e;
        }
    }
} 